package dao

import (
	"fmt"
	"git.supremind.info/product/box/vehicle/internal/dao/req"
	"git.supremind.info/product/box/vehicle/internal/util"
	"strconv"
)

type ModelData struct {
	EventId       string `json:"event_id"`
	Lane          string `json:"lane"`
	WheelsNumber  int    `json:"wheels_number"`
	Length        int    `json:"length"`
	AxlesNumber   int    `json:"axles_number"`
	Speed         int    `json:"speed"`
	VmrId         int    `json:"vmr_id"`
	VehicleType   string `json:"vehicle_type"`
	Gantry        string `json:"gantry"`
	AxleFormat    string `json:"axle_format"`
	SideImageUrl  string `json:"side_image_url"`
	HeadImageUrl  string `json:"head_image_url"`
	LicensePlate  `json:"license_plate"`
	PushKafkaTime util.Time   `json:"push_kafka_time"`
	EntryTime     util.Time   `json:"entry_time"`
	LeaveTime     util.Time   `json:"leave_time"`
	HeadTime      util.Time   `json:"head_time"`
	VmrTime       util.Time   `json:"vmr_time"`
	SideImage     Image       `json:"side_image"`
	HeadImage     Image       `json:"head_image"`
	Wheelbases    interface{} `json:"wheelbases"`
}

type LicensePlate struct {
	ImageUrl string `json:"image_url"`
	Color    string `json:"color"`
	Number   string `json:"number"`
	Image    `json:"image"`
}

type Image struct {
	Width  string `json:"width"`
	Height string `json:"height"`
}

type VehicleModelData struct {
	ID                 int      `gorm:"primary_key,AUTO_INCREMENT" json:"id"`
	IsDel              int      `gorm:"default:0" json:"isDel"`
	CreateBy           int      `gorm:"create_by" json:"createBy"`
	CreateTime         BaseTime `gorm:"create_time" json:"createTime"`
	UpdateBy           int      `json:"update_by"`
	UpdateTime         BaseTime `gorm:"update_time" json:"updateTime"`
	Gantry             string   `gorm:"gantry" json:"gantry"`
	EventId            string   `gorm:"event_id" json:"eventId"`
	CompanyId          int      `gorm:"company_id" json:"companyId"`
	OrganizationId     int      `gorm:"organization_id" json:"organizationId"`
	OrganizationPath   string   `gorm:"organization_path" json:"organizationPath"`
	Source             string   `gorm:"source" json:"source"`
	VehicleType        string   `gorm:"vehicle_type" json:"vehicleType"`
	BoxName            string   `gorm:"box_name" json:"boxName"`
	SerialNumber       string   `gorm:"serial_number" json:"serialNumber"`
	AxlesNumber        float64  `gorm:"axles_number" json:"axlesNumber"`
	WheelsNumber       float64  `gorm:"wheels_number" json:"wheelsNumber"`
	HazardousChemicals string   `gorm:"hazardous_chemicals" json:"hazardousChemicals"`
	Lane               string   `gorm:"lane" json:"lane"`
	EventTime          BaseTime `gorm:"event_time" json:"eventTime"`
	Data               string   `gorm:"data" json:"data"`
	PushStatus         int      `gorm:"push_status" json:"pushStatus"`
}

const (
	selectSql = "SELECT t1.id,t1.gantry,t1.event_id,t1.company_id,t1.organization_id,t1.source,t1.vehicle_type,t1.box_name,t1.serial_number,t1.axles_number,t1.wheels_number,t1.hazardous_chemicals,t1.lane,t1.event_time,t1.push_status,t1.data "
)

func (ac *VehicleModelData) TableName() string {
	return "vehicle_model_data"
}

func DeleteByIds(ids []int) {
	DB.Delete(&VehicleModelData{}, ids)
}

func GetUnPushModelHisDatas() []VehicleModelData {
	sql := selectSql + " from vehicle_model_data t1 order by t1.event_time desc LIMIT %d"
	var events []VehicleModelData
	r, _ := DB.Debug().Raw(sql, 50).Rows()
	defer r.Close()
	for r.Next() {
		var data VehicleModelData
		DB.ScanRows(r, &data)
		fmt.Print(data)
		events = append(events, data)
	}
	return events
}

func GetModelHisDataList(req req.ModelHisDataListReq) ([]VehicleModelData, int, error) {
	suffixSql := " from vehicle_model_data t1 left join vehicle_model_chemical t2 on t1.id = t2.event_id where 1 = 1 "

	var params []interface{}

	if util.IsNotBlank(req.StartTime) && util.IsNotBlank(req.EndTime) {
		suffixSql = suffixSql + " and t1.event_time between ? and ? "
		params = append(params, req.StartTime, req.EndTime)
	}

	if req.VehicleTypes != nil && len(req.VehicleTypes) > 0 {
		suffixSql = suffixSql + " and t1.vehicle_type in (?) "
		params = append(params, req.VehicleTypes)
	}

	if len(req.AxlesNumber) > 0 {
		if req.AxlesNumber == ">=6" {
			suffixSql = suffixSql + " and t1.axles_number >= ? "
			params = append(params, 6)
		} else {
			suffixSql = suffixSql + " and t1.axles_number = ? "
			axlesNumber, _ := strconv.Atoi(req.AxlesNumber)
			params = append(params, axlesNumber)
		}
	}

	if req.HazardousChemicals != nil && len(req.HazardousChemicals) > 0 {
		suffixSql = suffixSql + " and t2.hazardous_chemical in ? "
		params = append(params, req.HazardousChemicals)
	}

	countSql := "SELECT count(*) " + suffixSql
	count := QueryCount(countSql, params...)

	sql := selectSql + suffixSql + " group by t1.id order by t1.event_time desc LIMIT %d,%d"
	sql = fmt.Sprintf(sql, (req.PageNo-1)*req.PageSize, req.PageSize)

	var events []VehicleModelData
	r, _ := DB.Debug().Raw(sql, params...).Rows()
	defer r.Close()
	for r.Next() {
		var data VehicleModelData
		DB.ScanRows(r, &data)
		fmt.Print(data)
		events = append(events, data)
	}

	return events, count, nil
}

func SaveVehicleModelData(vehicleMode *VehicleModelData) int {
	DB.Debug().Create(&vehicleMode)
	return vehicleMode.ID
}
